﻿using System;
using System.Xml.Linq;
using System.Configuration;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.AdvancedAPIs;
using Newtonsoft.Json.Linq;
using QJY.Common;
using System.Linq;
using System.Data;
using Newtonsoft.Json;
using Senparc.Weixin.MP.TenPayLibV3;

namespace QJY.API
{
    public class WeiXinPay
    {
        public static void WXPayJsapi(ref Msg_Result msg, string userID, string orderID, string code, string userip, decimal ddje)
        {

            try
            {
                string wxappid = ConfigurationManager.AppSettings["wxappid"];
                string wxappsecret = ConfigurationManager.AppSettings["wxappsecret"];
                string wxmchid = ConfigurationManager.AppSettings["wxmchid"];
                string wxmchidkey = ConfigurationManager.AppSettings["wxmchidkey"];
                string TenPayV3Notify = ConfigurationManager.AppSettings["TenPayV3Notify"];

                TenPayV3Info ten = new TenPayV3Info(wxappid, wxappsecret, wxmchid, wxmchidkey, TenPayV3Notify);
                if (string.IsNullOrEmpty(code))
                {
                    msg.ErrorMsg = "您拒绝了授权！";
                    return;
                }

                if (string.IsNullOrEmpty(orderID))
                {
                    msg.ErrorMsg = "订单信息不存在！";
                    return;
                }
                DataTable dtReturn =new JH_Auth_BranchB().GetDTByCommand("select top 1 * from ddh where ddh='" + orderID + "'");

                if (dtReturn.Rows.Count != 1)
                {
                    msg.ErrorMsg = "订单信息错误！";
                    return;
                }

                if (dtReturn.Rows[0]["ddh"].ToString() == "")
                {
                    msg.ErrorMsg = "订单信息错误！";
                    return;
                }
                //if (order.payStatus != 0)
                //{
                //    msg.ErrorMsg = "订单状态有误!或您已支付.";
                //    return;
                //}
                //通过，用code换取access_token
                var openIdResult = OAuthApi.GetAccessToken(ten.AppId, ten.AppSecret, code);
                if (openIdResult.errcode != ReturnCode.请求成功)
                {
                    msg.ErrorMsg = "错误：" + openIdResult.errmsg;
                    return;
                }

                string timeStamp = "";
                string nonceStr = "";
                string paySign = "";

                Random MyRandom = new Random();
                int RandomNum = MyRandom.Next(1001, 9999);
                int RandomNum2 = MyRandom.Next(1001, 9999);
                string sp_billno = DateTime.Now.ToString("HHssmmfff") + RandomNum.ToString() + RandomNum2.ToString();
                dtReturn.Rows[0]["BusinessNo"] = sp_billno;
                new JH_Auth_BranchB().ExsSclarSql("UPDATE ddh SET BusinessNo='" + sp_billno + "' WHERE ddh='" + dtReturn.Rows[0]["ddh"].ToString() + "'");

                //当前时间 yyyyMMdd
                string date = DateTime.Now.ToString("yyyyMMdd");


                RequestHandler packageReqHandler = new RequestHandler(null);
                packageReqHandler.Init();
                timeStamp = TenPayV3Util.GetTimestamp();
                nonceStr = TenPayV3Util.GetNoncestr();
                packageReqHandler.SetParameter("appid", ten.AppId);       //公众账号ID
                packageReqHandler.SetParameter("mch_id", ten.MchId);          //商户号
                packageReqHandler.SetParameter("nonce_str", nonceStr);                    //随机字符串
                packageReqHandler.SetParameter("body", dtReturn.Rows[0]["lb"].ToString());    //商品信息
                packageReqHandler.SetParameter("out_trade_no", sp_billno);      //商家订单号
                packageReqHandler.SetParameter("total_fee", ((int)(ddje * 100)).ToString());                //商品金额,以分为单位(money * 100).ToString()
                packageReqHandler.SetParameter("spbill_create_ip", userip);  //用户的公网ip，不是商户服务器IP
                packageReqHandler.SetParameter("notify_url", ten.TenPayV3Notify);           //接收财付通通知的URL
                packageReqHandler.SetParameter("trade_type", TenPayV3Type.JSAPI.ToString());                        //交易类型
                packageReqHandler.SetParameter("openid", openIdResult.openid);                      //用户的openId

                string sign = packageReqHandler.CreateMd5Sign("key", ten.Key);
                packageReqHandler.SetParameter("sign", sign);                //签名
                string data = packageReqHandler.ParseXML();


                var result = TenPayV3.Unifiedorder(data);
                var res = XDocument.Parse(result);

                string prepayId = res.Element("xml").Element("prepay_id").Value;

                //设置支付参数
                RequestHandler paySignReqHandler = new RequestHandler(null);
                paySignReqHandler.SetParameter("appId", ten.AppId);
                paySignReqHandler.SetParameter("timeStamp", timeStamp);
                paySignReqHandler.SetParameter("nonceStr", nonceStr);
                paySignReqHandler.SetParameter("package", string.Format("prepay_id={0}", prepayId));
                paySignReqHandler.SetParameter("signType", "MD5");
                paySign = paySignReqHandler.CreateMd5Sign("key", ten.Key);
                msg.Result = new JObject(
                        new JProperty("appId", ten.AppId),
                        new JProperty("timeStamp", timeStamp),
                        new JProperty("nonceStr", nonceStr),
                        new JProperty("package", string.Format("prepay_id={0}", prepayId)),
                        new JProperty("signType", "MD5"),
                        new JProperty("paySign", paySign)
                    );
                CommonHelp.WriteLOG("支付成功");


            }
            catch (Exception ex)
            {
                string ss = ex.Message;
                msg.ErrorMsg = "支付订单失败";
                CommonHelp.WriteLOG(ex.Message + ex.StackTrace.ToString());
            }
        }

        public static string WXPayNotifyUrl()
        {
            try
            {
                CommonHelp.WriteLOG("开始反馈");
                ResponseHandler resHandler = new ResponseHandler(null);

                string return_code = resHandler.GetParameter("return_code");
                string return_msg = resHandler.GetParameter("return_msg");

                resHandler.SetKey(ConfigurationManager.AppSettings["wxmchidkey"]);
                //验证请求是否从微信发过来（安全）
                if (resHandler.IsTenpaySign())
                {

                    //正确的订单处理

                    //修改订单状态为已支付
                    string transaction_id = resHandler.GetParameter("transaction_id");
                    string out_trade_no = resHandler.GetParameter("out_trade_no"); //订单号码
                    string total_fee = resHandler.GetParameter("total_fee");  //订单金额

                    CommonHelp.WriteLOG("反馈：订单号" + out_trade_no + "金额" + total_fee);

                    string ddje = (int.Parse(total_fee) / 100).ToString();


                    //更新订单支付金额和支付状态
                    //new JWGL_BMJF().SearchXsdjksbmupdate(out_trade_no, ddje, "");



                    //验证订单号
                    //BW_Order_Header order = new OrderService().getOrderByBNO(out_trade_no);
                    //if (order == null)
                    //{
                    //    throw new Exception("订单信息不存在!" + out_trade_no);
                    //}
                    //if (order.OrderID == "" || order.ActualAmount <= 0)
                    //{
                    //    throw new Exception("订单信息错误!" + out_trade_no);
                    //}
                    //if (order.Status != 0)
                    //{
                    //    throw new Exception("订单状态有误!或您已支付");
                    //}
                    //if (order.ActualAmount <= 0 || ((int)(order.ActualAmount * 100)).ToString() != total_fee)
                    //{
                    //    throw new Exception("订单金额有误!");
                    //}
                    //else//正常支付
                    //{
                    //    DbHelperSQLJW.ExecuteSql("UPDATE BW_Order_Header SET Status=1,payStatus = 1,PayTime=GETDATE(),Payment=3 WHERE OrderID='" + order.OrderID + "' ");
                    //}
                }

                string xml = string.Format(@"<xml>
                   <return_code><![CDATA[{0}]]></return_code>
                   <return_msg><![CDATA[{1}]]></return_msg>
                </xml>", return_code, return_msg);

                return xml;
            }
            catch (Exception ex)
            {
                CommonHelp.WriteLOG(ex.Message);
            }
            return "wrong";
        }
    }
}
